package Thread;
class Counter{
    private int count = 0;
    public synchronized void increment(){   //相当于对this加锁，
        count++;
    }
    public void add(){
        synchronized(this){
            count++;
        }
    }
    public int getCount(){
        return count;
    }
}
class CounterStatc{
    private static int count1 = 0;  //静态方法只能调用静态变量
     public static  void increment(){
    synchronized(CounterStatc.class){
        count1++;
    }
    }
}
public class Demo18 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(()->{
        for(int i = 0; i < 10000; i++){
            synchronized(counter){
                counter.increment();
            }  //最外层是真正加锁解锁的
        }
    });
        Thread t2 = new Thread(()->{
            for(int i = 0; i < 10000; i++){
                synchronized(counter){  //嵌套锁不会导致线程安全问题，因为synchronized可重入
                                        //加锁成功后再次加锁不会阻塞，而是正常向下进行
                    //可重入锁的实现原理关键在于让锁对象内部保存，保存哪个线程持有这个锁，后续有线程针对这个锁加锁对比线程
                    counter.increment();
                }

            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.getCount());
    }
}
